package com.buba.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.buba.mapper.*;
import com.buba.service.SparePartsService;
import com.buba.service.WareDetailsService;
import entity.sparemanage.SpareLedger;
import entity.sparemanage.SpareParts;
import entity.sparemanage.WareDetails;
import entity.sparemanage.Warehousing;
import com.buba.service.WarehousingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import entity.sparemanage.dto.*;
import entity.sparemanage.vo.*;
import entity.system.CodeRules;
import feign.systemFeign;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.PageResult;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 入库记录表 服务实现类
 * </p>
 *
 * @author beisheng
 * @since 2023-05-18
 */
@Service
public class WarehousingServiceImpl extends ServiceImpl<WarehousingMapper, Warehousing> implements WarehousingService {

    @Autowired
    private WarehousingMapper warehousingMapper;

    @Autowired
    private systemFeign systemFeign;

    @Autowired
    private WareDetailsMapper wareDetailsMapper;

    @Autowired
    private SpareLedgerMapper spareLedgerMapper;

    @Autowired
    private SparePartsService sparePartsService;

    @Autowired
    private SpareTypesMapper spareTypesMapper;
    /* *
     * @Author: beisheng
     * @Descriprion: 分页模糊查入库管理列表
     * @Date: 2023/5/25 8:42
     * @Return: common.R
     * @Param: [warehouseDto]
     */

    @Override
    public PageResult selAllWareHouse(warehouseDto warehouseDto) {
        //1.模糊条件判断
        warehouseQueryWrapper queryWrapper = new warehouseQueryWrapper();
        QueryWrapper<Warehousing> queryWrappers = queryWrapper.queryWrapper(warehouseDto);
        //2.分页查询数据
        Page<Warehousing> warehousingPage = new Page<>(warehouseDto.getPage(),warehouseDto.getPageSize());
        Page<Warehousing> warehousingLists = warehousingMapper.selectPage(warehousingPage, queryWrappers);
        List<Warehousing> warehousingList = warehousingMapper.selectList(new QueryWrapper<Warehousing>().eq("delete_flag", 0));
        List<Warehousing> records = warehousingLists.getRecords();
        List<wareHosuseVo> wareHosuseVos = new ArrayList<>();
        for (Warehousing record : records) {
            wareHosuseVo wareHosuseVo = new wareHosuseVo();
            BeanUtils.copyProperties(record,wareHosuseVo);
            //3.查询仓库信息
            wareVo wareVo = systemFeign.selOneWareHouse(record.getWarehouseId());
            wareHosuseVo.setWareVo(wareVo);
            //4.查询入库申请人及所在部门
            PeopleVo peopleVo = systemFeign.selOnePeople(record.getApplicantId());
            wareHosuseVo.setApplyPeople(peopleVo);
            //5.查询入库申请人
            if (record.getWarePersonid()!=null){
                PeopleVo peopleVo1 = systemFeign.selOnePeople(record.getWarePersonid());
                wareHosuseVo.setWarePeople(peopleVo1);
            }
            wareHosuseVos.add(wareHosuseVo);
        }
        return new PageResult(warehouseDto.getPage(),warehouseDto.getPageSize(),warehousingList.size(),wareHosuseVos);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insetWareHouse(insetWareHouseDto insetWareHouseDto) {
        //1.新增入库记录基本信息
        //1.1 查询规则生成入库单号
        CodeRules bj = systemFeign.selAllRules("RK");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(bj.getDateTime());
        String format = simpleDateFormat.format(new Date());
        List<Warehousing> warehousingList = warehousingMapper.selectList(new QueryWrapper<Warehousing>().eq("delete_flag", 0));
        String code = bj.getPrefix()+format+"0"+(warehousingList.size()+1);
        Warehousing warehousing = new Warehousing();
        BeanUtils.copyProperties(insetWareHouseDto,warehousing);
        warehousing.setTotalInbound(insetWareHouseDto.getTotalInbound());
        warehousing.setWareCode(code);
        warehousing.setCreateTime(new Date());
        warehousing.setUpdateTime(new Date());
        warehousing.setDeleteFlag(0);
        try {
            warehousingMapper.insert(warehousing);
        }catch (Exception e){
            throw new RuntimeException("新增入库记录基本信息失败",e);
        }

        List<spareLedgerDtos> spareList = insetWareHouseDto.getSpareList();
        for (spareLedgerDtos spareLedgerDtos : spareList) {
            //2.新增入库明细
            WareDetails wareDetails = new WareDetails();
            wareDetails.setSpId(spareLedgerDtos.getSpId());
            wareDetails.setLnventoryLimit(spareLedgerDtos.getUpperInventory().toString());
            wareDetails.setLoverLimit(spareLedgerDtos.getLowerInventory().toString());
            wareDetails.setNowLimit(spareLedgerDtos.getTotalInventory().toString());
            wareDetails.setWareNumber(spareLedgerDtos.getReceiptQuantity());
            wareDetails.setWarehoseCode(spareLedgerDtos.getPosition());
            wareDetails.setUseId(warehousing.getSpId());
            wareDetails.setCreateTime(new Date());
            wareDetails.setUpdateTime(new Date());
            wareDetails.setFlag(1);
            try {
                wareDetailsMapper.insert(wareDetails);
            }catch (Exception e){
                throw new RuntimeException("新增入库明细失败",e);
            }
            //3.更改备件总库存
            SpareLedger spareLedger = spareLedgerMapper.selectById(spareLedgerDtos.getSpId());
            SpareLedger spareLedger1 = new SpareLedger();
            spareLedger1.setTotalInventory(spareLedger.getTotalInventory()+Integer.valueOf(spareLedgerDtos.getReceiptQuantity()));
            spareLedger1.setSpId(spareLedgerDtos.getSpId());
            try {
                spareLedgerMapper.updateById(spareLedger1);
            }catch (Exception e){
                throw new RuntimeException("修改备件总库存失败",e);
            }
        }
    }

    /* *
     * @Author: beisheng
     * @Descriprion: 根据入库申请ID查询详细信息
     * @Date: 2023/5/30 14:20
     * @Return: common.R
     * @Param: [spId]
     */

    @Override
    public selOneCollectingVo selOneCollecting(Integer spId) {
        //1.根据ID查询基本信息
        Warehousing warehousing = warehousingMapper.selectById(spId);
        //2.判断入库类型
        String purchaseOrder = warehousing.getPurchaseOrder();
        //3.采购入库需要多查询采购单号
        selByPartsIdDto selByPartsIdDtos  = null;
        if (warehousing.getWareType() == 2){
            SpareParts spareParts = sparePartsService.getOne(new QueryWrapper<SpareParts>().eq("procure_code", purchaseOrder));
            selByPartsIdDtos = sparePartsService.selByPartsId(spareParts.getSpId());
        }
        //4.查询仓库信息
        wareVo wareVo = systemFeign.selOneWareHouse(warehousing.getWarehouseId());
        //5.查询入库人员
        PeopleVo peopleVo = systemFeign.selOnePeople(warehousing.getWarePersonid());
        //6.查询入库明细
        List<WareDetails> wareDetailsList = wareDetailsMapper.selectList(new QueryWrapper<WareDetails>().eq("use_id", warehousing.getSpId()));
        //7.查询入库申请人
        PeopleVo peopleVos = systemFeign.selOnePeople(warehousing.getApplicantId());

        SelOneCollectionVo selOneCollectionVo = new SelOneCollectionVo();

        selOneCollectingVo selOneCollectingVos = selOneCollectionVo.SelOneCollection(warehousing, wareVo, peopleVo, selByPartsIdDtos, peopleVos);

        List<spareLedgerDtos> spareList  = new ArrayList<>();
        for (WareDetails wareDetails : wareDetailsList) {
            spareLedgerDtos spareLedgerDtos = new spareLedgerDtos();
            SpareLedger spareLedger = spareLedgerMapper.selectById(wareDetails.getSpId());
            spareLedger.setSpTypeName(spareTypesMapper.selectById(spareLedger.getSpTypeId()).getSpTypename());
            BeanUtils.copyProperties(spareLedger,spareLedgerDtos);
            spareLedgerDtos.setPosition(wareDetails.getWarehoseCode());
            spareLedgerDtos.setReceiptQuantity(wareDetails.getWareNumber());
            spareList.add(spareLedgerDtos);
        }

        selOneCollectingVos.setSpareList(spareList);
        //8.返回数据
        return selOneCollectingVos;
    }

    /* *
     * @Author: beisheng
     * @Descriprion: 修改入库单信息
     * @Date: 2023/5/30 19:15
     * @Return: common.R
     * @Param: [insetWareHouseDto]
     */

    @Override
    public void updateCollection(insetWareHouseDto insetWareHouseDto) {
        Warehousing warehousing = new Warehousing();
        BeanUtils.copyProperties(insetWareHouseDto,warehousing);
        warehousing.setTotalInbound(insetWareHouseDto.getTotalInbound());
        warehousing.setUpdateTime(new Date());
        warehousingMapper.updateById(warehousing);
        List<WareDetails> wareDetailsList = wareDetailsMapper.selectList(new QueryWrapper<WareDetails>().eq("use_id", insetWareHouseDto.getSpId()));
        for (WareDetails wareDetails : wareDetailsList) {
            SpareLedger spareLedger = spareLedgerMapper.selectById(wareDetails.getSpId());
            spareLedger.setTotalInventory(Integer.valueOf(spareLedger.getTotalInventory())-Integer.valueOf(wareDetails.getWareNumber()));
            spareLedgerMapper.updateById(spareLedger);
        }
        wareDetailsMapper.delete(new QueryWrapper<WareDetails>().eq("use_id",insetWareHouseDto.getSpId()));
        for (spareLedgerDtos spareLedgerDtos : insetWareHouseDto.getSpareList()) {
            //2.新增入库明细
            WareDetails wareDetails = new WareDetails();
            wareDetails.setSpId(spareLedgerDtos.getSpId());
            wareDetails.setLnventoryLimit(spareLedgerDtos.getUpperInventory().toString());
            wareDetails.setLoverLimit(spareLedgerDtos.getLowerInventory().toString());
            wareDetails.setNowLimit(spareLedgerDtos.getTotalInventory().toString());
            wareDetails.setWareNumber(spareLedgerDtos.getReceiptQuantity());
            wareDetails.setWarehoseCode(spareLedgerDtos.getPosition());
            wareDetails.setUseId(warehousing.getSpId());
            wareDetails.setCreateTime(new Date());
            wareDetails.setUpdateTime(new Date());
            wareDetails.setFlag(1);
            try {
                wareDetailsMapper.insert(wareDetails);
            }catch (Exception e){
                throw new RuntimeException("新增入库明细失败",e);
            }
            //3.更改备件总库存
            SpareLedger spareLedger = spareLedgerMapper.selectById(spareLedgerDtos.getSpId());
            SpareLedger spareLedger1 = new SpareLedger();
            spareLedger1.setTotalInventory(spareLedger.getTotalInventory()+Integer.valueOf(spareLedgerDtos.getReceiptQuantity()));
            spareLedger1.setSpId(spareLedgerDtos.getSpId());
            try {
                spareLedgerMapper.updateById(spareLedger1);
            }catch (Exception e){
                throw new RuntimeException("修改备件总库存失败",e);
            }
        }
    }
}
